#include "log.hpp"
#include <cstdio>
#include <iostream>
#include <string>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>

const int WRITE_SIZE = 0x400;
const int SEND_SIZE = 0x400;

const std::string file_prefix = "./file/";

struct sockaddr_in server1, server2;
int sock1, sock2;

uint16_t serverport1, serverport2;
std::string serverip;

static void usage(std::string proc)
{
    std::cout << "\nUsage:" << proc << " serverIp serverPort1 serverPort2\n" << std::endl;
}

bool process(FILE* r_fp, FILE* w_fp, int flag)
{
    char send_buf[SEND_SIZE];
    char rece_buf[WRITE_SIZE];
    auto sock = flag == 1 ? sock1 : sock2;
    auto server = flag == 1 ? server1 : server2;
    std::cout << "\ncurrent ip:" << inet_ntoa(server.sin_addr) << std::endl;
    std::cout << "current port:" << ntohs(server.sin_port) << std::endl;
    if (connect(sock, (struct sockaddr*)&server, sizeof server) < 0) return false;

    while (fgets(send_buf, sizeof send_buf, r_fp)) {
        write(sock, send_buf, strlen(send_buf));
        memset(rece_buf, 0, sizeof rece_buf);

        if (read(sock, rece_buf, sizeof rece_buf) > 0) {
            printf("have received: %s", rece_buf);
            fprintf(w_fp, "%s", rece_buf);
        }
        memset(send_buf, 0, sizeof send_buf);
    }
    return true;
}

int main(int argc, char *argv[])
{
    if (argc != 4) {
        usage(argv[0]);
        exit(1);
    }

    sock1 = socket(AF_INET, SOCK_DGRAM, 0);
    sock2 = socket(AF_INET, SOCK_DGRAM, 0);

    if (sock1 < 0 || sock2 < 0) {
        std::cerr << "socket error." << std::endl;
        exit(2);
    }

    serverport1 = atoi(argv[2]), serverport2 = atoi(argv[3]);
    serverip = argv[1];

    memset(&server1, 0, sizeof server1);
    memset(&server2, 0, sizeof server2);

    server1.sin_family = AF_INET;
    server1.sin_port = htons(atoi(argv[2]));
    server1.sin_addr.s_addr = inet_addr(argv[1]);

    server2.sin_family = AF_INET;
    server2.sin_port = htons(atoi(argv[3]));
    server2.sin_addr.s_addr = inet_addr(argv[1]);
    
    auto fp_a1 = fopen((file_prefix + "A1").c_str(), "r");
    auto fp_a2 = fopen((file_prefix + "A2").c_str(), "r");
    auto fp_b1 = fopen((file_prefix + "B1").c_str(), "w");
    auto fp_b2 = fopen((file_prefix + "B2").c_str(), "w");

    if (!fp_a1 || !fp_a2 || !fp_b1 || !fp_b2) {
        std::cerr << "open file error." << std::endl;
        exit(2);
    }

    std::cout << "process..." << std::endl;
    if (!process(fp_a1, fp_b1, 1) || !process(fp_a2, fp_b2, 2)) {
        std::cerr << "process error: connect failed." << std::endl;
        exit(2);
    }

    return 0;
}

